

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.ico">
  <link rel="icon" href="/img/favicon.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="叶尘的技术升级小木屋">
  <meta name="author" content="叶尘">
  <meta name="keywords" content="">
  
  <title>Spring注解开发之组件注册 - 叶尘的技术升级小木屋</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10.7.2/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/shubiao.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/gundongtiao.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/daziyanse.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/toubudaziji.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.yechen-blog.cn","root":"/","version":"1.8.11","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>YECHEN</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-qrcode"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/playlist/">
                <i class="iconfont icon-music"></i>
                音乐
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" target="_self" role="button"
                 data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-books"></i>
                链接
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/">
                    
                    主题博客
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/guide/">
                    
                    配置指南
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    图标用法
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://www.bilibili.com">
                    
                    哔哩哔哩
                  </a>
                
              </div>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/banner.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Spring注解开发之组件注册">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      叶尘
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-09-16 19:54" pubdate>
        星期四, 九月 16日 2021, 7:54 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.5k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      47
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Spring注解开发之组件注册</h1>
            
            <div class="markdown-body">
              <h3 id="一、使用注解开发"><a href="#一、使用注解开发" class="headerlink" title="一、使用注解开发"></a>一、使用注解开发</h3><p>1、创建 Maven 管理项目，引入 Spring 核心依赖和 Junit 测试依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-context<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>5.3.9<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>4.13.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br></code></pre></td></tr></table></figure>



<p>2、编写实体类 Person，写上有参、无参构造方法，setter 和 getter，toString 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> Integer age;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">()</span> </span>&#123;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">(String name, Integer age)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.name = name;<br>        <span class="hljs-keyword">this</span>.age = age;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> name;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.name = name;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> age;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(Integer age)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.age = age;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Person&#123;&quot;</span> +<br>                <span class="hljs-string">&quot;name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +<br>                <span class="hljs-string">&quot;, age=&quot;</span> + age +<br>                <span class="hljs-string">&#x27;&#125;&#x27;</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>3、创建配置类 MyConfig，使用 <code>@Configuration</code> 注解表示此类是一个配置类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 告诉 Spring 这是一个配置类</span><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConfig</span> </span>&#123;<br><br>    <span class="hljs-comment">/*</span><br><span class="hljs-comment">    组件在容器中的名称（id）可以有两个方法指定：</span><br><span class="hljs-comment">        1、默认使用方法名作为 bean 的名称</span><br><span class="hljs-comment">        2、在 @Bean 注解中有 value 属性，可以指定 bean 的名称</span><br><span class="hljs-comment">    此时这个 bean 在容器中的 id 就是 person01    </span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Bean(&quot;person01&quot;)</span><span class="hljs-comment">// 向容器中注册组件</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">person</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;lisi&quot;</span>, <span class="hljs-number">20</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>4、测试，使用 Junit 单元测试，获取容器，从容器中获取 bean，这里要注意获取配置类需要使用类 <code>AnnotationConfigApplicationContext</code>，不在是之前 xml 配置文件时的 <code>ClassPathXmlApplicationContext</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 使用注解开发</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testAnnotationConfig</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-comment">// xml 配置文件方式</span><br>    <span class="hljs-comment">/*ApplicationContext context = new ClassPathXmlApplicationContext(&quot;bean.xml&quot;);</span><br><span class="hljs-comment">    Person person = context.getBean(&quot;person&quot;, Person.class);</span><br><span class="hljs-comment">    System.out.println(person);*/</span><br><br>    <span class="hljs-comment">// 注解方式</span><br>    AnnotationConfigApplicationContext context = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext(MyConfig.class);<br>    Person person = context.getBean(<span class="hljs-string">&quot;person01&quot;</span>, Person.class);<br>    System.out.println(person);<br><br>    <span class="hljs-comment">// 查看容器中所有组件的名称</span><br>    String[] names = context.getBeanDefinitionNames();<br>    <span class="hljs-keyword">for</span> (String name : names) &#123;<br>        System.out.println(<span class="hljs-string">&quot;在容器中的名称：&quot;</span> + name);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.4732hodl7hk0.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<h3 id="二、添加包扫描"><a href="#二、添加包扫描" class="headerlink" title="二、添加包扫描"></a>二、添加包扫描</h3><p>包扫描使用的是 <code>@ComponentScan</code> 注解，可以指定要扫描的组件的范围。</p>
<h4 id="1-ComponentScan-注解"><a href="#1-ComponentScan-注解" class="headerlink" title="1. @ComponentScan 注解"></a>1. @ComponentScan 注解</h4><p>简单使用 <code>@ComponentScan</code> 注解，扫描 dao、service、controller 包下的类</p>
<p>创建三个类，分别是 PersonDao、PersonService、PersonController，同时使用不同的注解表示其是一个组件要加入到 ioc 容器中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Repository</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PersonDao</span> </span>&#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Service</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PersonService</span> </span>&#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Controller</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PersonController</span> </span>&#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>此时在配置类中就可以使用 <code>@ComponentScan</code> 注解的 value 属性指定包扫描范围</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@ComponentScan(value = &quot;cn.yechen&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConfig</span> </span>&#123;<br>    <br>	<span class="hljs-comment">// 向容器中注册组件</span><br>    <span class="hljs-meta">@Bean(&quot;person01&quot;)</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">person</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;lisi&quot;</span>, <span class="hljs-number">20</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试</p>
<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.61882kovxwc0.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<h4 id="2-excludeFilters-属性"><a href="#2-excludeFilters-属性" class="headerlink" title="2. excludeFilters 属性"></a>2. excludeFilters 属性</h4><p>可以使用 <code>excludeFilters</code> 属性配置排除规则，及在扫描组件时排除掉一些不添加到 ioc 容器中去，<strong>其值是一个 Filter 数组</strong>，通过 type 指定过滤的规则，可以是按注解、aspectJ 表达式、正则表达式来指定过滤的类型，classes 指定过滤的类。</p>
<p><strong>详细讲一下过滤规则：</strong></p>
<ul>
<li><code>FilterType.ANNOTATION</code>：按照注解方式，classes 中指定注解类，如 <code>classes = &#123;Controller.class, Repository.class&#125;</code></li>
<li><code>FilterType.ASSIGNABLE_TYPE</code>：按照指定的类型，classes 中指定具体类，如 <code>classes = &#123;PersonController.class&#125;</code></li>
<li><code>FilterType.ASPECTJ</code>：使用 ASPECTJ 表达式，不常用</li>
<li><code>FilterType.REGEX</code>：使用正则表达式</li>
<li><code>FilterType.CUSTOM</code>：使用自定义规则，classes 中指定自定义类型过滤类，该类要实现 <code>TypeFilter</code> 接口，并重写 <code>match</code> 方法，value 指定的包下的每一个类都会进入到 match 方法，只有返回值为 true 时，这个类才会符合过滤条件</li>
</ul>
<p><strong>使用 FilterType.ANNOTATION：</strong>这里就是排除了使用 @Controller 和 @Service 注解的组件加入 ioc 容器中，最后在容器中的只有 personDao</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@ComponentScan(value = &quot;cn.yechen&quot;, excludeFilters = &#123;@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = &#123;Controller.class, Service.class&#125;)&#125;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConfig</span> </span>&#123;<br>    <br>	<span class="hljs-comment">// 向容器中注册组件</span><br>    <span class="hljs-meta">@Bean(&quot;person01&quot;)</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">person</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;lisi&quot;</span>, <span class="hljs-number">20</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试</p>
<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.53nrx11mxl00.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<p><strong>使用 FilterType.ASSIGNABLE_TYPE</strong>：直接指定排除的类，这里排除 PersonController 类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ComponentScan(value = &quot;cn.yechen&quot;, excludeFilters = &#123;@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = &#123;PersonController.class&#125;)&#125;)</span><br></code></pre></td></tr></table></figure>



<p><strong>使用 FilterType.CUSTOM</strong>：自定义规则，类要实现 TypeFilter 接口</p>
<p>创建 MyTypeFilter 类实现 TypeFilter 接口，重写其方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTypeFilter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">TypeFilter</span> </span>&#123;<br>    <span class="hljs-comment">/*</span><br><span class="hljs-comment">        MetadataReader：读取到当前正在扫描的类的信息</span><br><span class="hljs-comment">        MetadataReaderFactory：可以获取到其他任何类的信息</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">match</span><span class="hljs-params">(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        <span class="hljs-comment">// 获取当前正在扫描的注解信息</span><br>        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();<br>        <span class="hljs-comment">// 获取当前正在扫描的类的信息</span><br>        ClassMetadata classMetadata = metadataReader.getClassMetadata();<br>        <span class="hljs-comment">// 获取当前正在扫描的资源信息（类的路径）</span><br>        Resource resource = metadataReader.getResource();<br><br>        String className = classMetadata.getClassName();<br>        System.out.println(<span class="hljs-string">&quot;自定以类型过滤器输出类名：&quot;</span> + className);<br>        <span class="hljs-comment">// 这里就是为了过滤名称包含 Controller 或 MyTypeFilter 的组件加入容器</span><br>        <span class="hljs-keyword">return</span> className.contains(<span class="hljs-string">&quot;Controller&quot;</span>) || className.contains(<span class="hljs-string">&quot;MyTypeFilter&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>此时通过 16 行的输出语句可以观察到，value 指定的包下的每一个类都会进入到 match 方法，只有返回值为 true 时，这个类才会符合过滤条件</p>
<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.gxer34os9mo.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ComponentScan(value = &quot;cn.yechen&quot;, excludeFilters = &#123;@ComponentScan.Filter(type = FilterType.CUSTOM, classes = &#123;MyTypeFilter.class&#125;)&#125;)</span><br></code></pre></td></tr></table></figure>



<h4 id="3-includeFilters-属性"><a href="#3-includeFilters-属性" class="headerlink" title="3. includeFilters 属性"></a>3. includeFilters 属性</h4><p>可以使用 <code>includeFilters </code> 注解来指定扫描策略，其作用和 <code>excludeFilters </code> 相反，就是指定要将那些组件注册到 ioc 容器中去，使用方式和 <code>excludeFilters</code> 相似，都是配置 Filter，这里就不赘述了。</p>
<p>但是在使用 includeFilters  是，要将默认的扫描规则关闭掉，即设置 useDefaultFilters 属性为 false。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ComponentScan(value = &quot;cn.yechen&quot;, useDefaultFilters = false, includeFilters = &#123;@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = &#123;Controller.class, Repository.class&#125;)&#125;</span><br></code></pre></td></tr></table></figure>



<h4 id="4-ComponentScans-注解"><a href="#4-ComponentScans-注解" class="headerlink" title="4. @ComponentScans 注解"></a>4. @ComponentScans 注解</h4><p><code>@ComponentScan</code> 是一个重复注解，可以使用多次，指定多个扫描规则，为了方便，也可以使用<code>@ComponentScans</code>， 该注解中可以指定多个包扫描规则。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ComponentScans(</span><br><span class="hljs-meta">        &#123;</span><br><span class="hljs-meta">                @ComponentScan(value = &quot;cn.yechen&quot;), </span><br><span class="hljs-meta">                @ComponentScan(excludeFilters = &#123;@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = &#123;Controller.class, Service.class&#125;)&#125;)</span><br><span class="hljs-meta">        &#125;)</span><br></code></pre></td></tr></table></figure>



<h3 id="三、-Scope-注解"><a href="#三、-Scope-注解" class="headerlink" title="三、@Scope 注解"></a>三、@Scope 注解</h3><p><code>@Scope</code> 注解可以指定当前 bean 是多实例还是单实例，它源码中有这些值</p>
<ul>
<li><code>ConfigurableBeanFactory.SCOPE_PROTOTYPE</code>：<strong>多实例的</strong>，使用 @Scope(“prototype”) 指定</li>
<li><code>ConfigurableBeanFactory.SCOPE_SINGLETON</code>：<strong>单实例的</strong>，默认值</li>
<li><code>org.springframework.web.context.WebApplicationContext.SCOPE_REQUEST</code>：<strong>同一次请求创建一个实例</strong>，使用 @Scope(“request”) 指定</li>
<li><code>org.springframework.web.context.WebApplicationContext.SCOPE_SESSION</code>：<strong>同一次 session 创建一个实例</strong>，使用 @Scope(“session”) 指定</li>
</ul>
<blockquote>
<p>指定默认单实例对象时，ioc 容器启动会调用方法创建对象放到 ioc 容器中，以后每次获取就是直接从容器中拿，就不会调用方法了。</p>
</blockquote>
<blockquote>
<p>指定多实例对象时，ioc 容器启动时不会调用方法创建对象放在容器中，是在每次获取 bean 时调用方法创建对象放入 ioc 容器中，每次获取都会调用方法创建对象。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Scope(&quot;prototype&quot;)</span> <span class="hljs-comment">// 这里就指定了当前对象在容器中是多实例的，在获取 bean 时才调用方法创建对象放入容器</span><br><span class="hljs-meta">@Bean(&quot;lisi&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">person</span><span class="hljs-params">()</span> </span>&#123;<br>    System.out.println(<span class="hljs-string">&quot;lisi 被创建了&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;lisi&quot;</span>, <span class="hljs-number">20</span>);<br>&#125;<br></code></pre></td></tr></table></figure>



<blockquote>
<p> <strong>懒加载</strong>：在容器启动时不创建对象，第一次获取 bean 时才创建对象，并将对象放入容器中，<strong>懒加载时针对单实例对象的。使用 @Lazy 注解</strong></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Lazy</span><span class="hljs-comment">// 懒加载，当前对象时单例的，本来在容器启动时就会创建对象放到容器中，但是现在使用了懒加载，就会在获取 bean 时才调用方法创建对象放入容器</span><br><span class="hljs-meta">@Bean(&quot;lisi&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">person</span><span class="hljs-params">()</span> </span>&#123;<br>    System.out.println(<span class="hljs-string">&quot;lisi 被创建了&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;lisi&quot;</span>, <span class="hljs-number">20</span>);<br>&#125;<br></code></pre></td></tr></table></figure>





<h3 id="四、-Conditional-注解"><a href="#四、-Conditional-注解" class="headerlink" title="四、@Conditional 注解"></a>四、@Conditional 注解</h3><p><code>@Conditional</code> 注解：<strong>会按照一定的条件进行判断，满足条件才将 bean 注册到容器中</strong>，可以标注在方法上，也可以标注在配置类上，只有当条件符合的时候才注册 bean。</p>
<blockquote>
<p>现在有一个需求：当前电脑是 window 系统时，就在容器中放置 bill 这个对象，当前电脑是 linux 系统时，就在容器中放置 linus 这个对象</p>
</blockquote>
<p>此时，就可以使用 @Conditional 注解指定条件判断，动态的注册 bean 了</p>
<p>首先需要自定义类实现 <code>Condition</code> 接口，重写 <code>matches</code> 方法，只有返回值为 true 时才会将对象注册到容器中，那么我们就编写两个实现类分别判断是 windows 还是 linux</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 判断当前系统是否是 Linux 系统</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LinuxConditional</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Condition</span> </span>&#123;<br>    <span class="hljs-comment">/*</span><br><span class="hljs-comment">        ConditionContext：判断条件能使用的上下文（环境）</span><br><span class="hljs-comment">        AnnotatedTypeMetadata：注释信息</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">matches</span><span class="hljs-params">(ConditionContext context, AnnotatedTypeMetadata metadata)</span> </span>&#123;<br>        <span class="hljs-comment">// 判断是否是 Linux 系统</span><br>        Environment environment = context.getEnvironment();<br>        String osName = environment.getProperty(<span class="hljs-string">&quot;os.name&quot;</span>);<br><br>        <span class="hljs-keyword">return</span> osName.contains(<span class="hljs-string">&quot;Linux&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 判断当前系统是否是 windows</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WindowsConditional</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Condition</span> </span>&#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">matches</span><span class="hljs-params">(ConditionContext context, AnnotatedTypeMetadata metadata)</span> </span>&#123;<br>        <span class="hljs-comment">// 判断是否是 Windows 系统</span><br>        Environment environment = context.getEnvironment();<br>        String osName = environment.getProperty(<span class="hljs-string">&quot;os.name&quot;</span>);<br><br>        <span class="hljs-keyword">return</span> osName.contains(<span class="hljs-string">&quot;Windows&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>之后就可在注册 bean 的方法上使用 @Conditional 注解了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Conditional(&#123;WindowsConditional.class&#125;)</span><br><span class="hljs-meta">@Bean(&quot;bill&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">person1</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;Bill Getes&quot;</span>, <span class="hljs-number">62</span>);<br>&#125;<br><br><span class="hljs-meta">@Conditional(&#123;LinuxConditional.class&#125;)</span><br><span class="hljs-meta">@Bean(&quot;linus&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">person2</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-string">&quot;Linus&quot;</span>, <span class="hljs-number">60</span>);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 测试 Conditional 注解</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testConditional</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-comment">// 获取容器</span><br>    AnnotationConfigApplicationContext context = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext(MyConfig2.class);<br><br>    <span class="hljs-comment">// 获取环境变量的值：Windows 10</span><br>    ConfigurableEnvironment environment = context.getEnvironment();<br>    String property = environment.getProperty(<span class="hljs-string">&quot;os.name&quot;</span>);<br>    System.out.println(property);<span class="hljs-comment">// Windows 10</span><br><br>    <span class="hljs-comment">// 获取所有 Person 类型的组件</span><br>    Map&lt;String, Person&gt; beansOfType = context.getBeansOfType(Person.class);<br>    System.out.println(beansOfType);<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.11lw9dm1pr5c.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<p>由于当前使用的是 windows 系统，所以将 bill 注册到了容器中。</p>
<h3 id="五、-Import-注解"><a href="#五、-Import-注解" class="headerlink" title="五、@Import 注解"></a>五、@Import 注解</h3><p><code>@Import</code> 注解标注在配置类上面，可以快速将一个组件注册到 ioc 容器中，有三种方法注册。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Target(ElementType.TYPE)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-meta">@Documented</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> Import &#123;<br><br>   <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * &#123;<span class="hljs-doctag">@link</span> Configuration <span class="hljs-doctag">@Configuration</span>&#125;, &#123;<span class="hljs-doctag">@link</span> ImportSelector&#125;,</span><br><span class="hljs-comment">    * &#123;<span class="hljs-doctag">@link</span> ImportBeanDefinitionRegistrar&#125;, or regular component classes to import.</span><br><span class="hljs-comment">    */</span><br>   Class&lt;?&gt;[] value();<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>这里先编写两个实体类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Color</span> </span>&#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Red</span> </span>&#123;<br>&#125;<br></code></pre></td></tr></table></figure>



<h4 id="1-直接写-class-导入组件"><a href="#1-直接写-class-导入组件" class="headerlink" title="1. 直接写 class 导入组件"></a>1. 直接写 class 导入组件</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@Import(value = &#123;Color.class, Red.class&#125;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConfig2</span> </span>&#123;<br>    <br>&#125;<br></code></pre></td></tr></table></figure>

<p>此时这两个组件就被注册到容器中了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 测试 Import 注解</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testImport</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-comment">// 获取容器</span><br>    AnnotationConfigApplicationContext context = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext(MyConfig2.class);<br><br>    <span class="hljs-comment">// 查看容器中所有组件的名称</span><br>    String[] names = context.getBeanDefinitionNames();<br>    <span class="hljs-keyword">for</span> (String name : names) &#123;<br>        System.out.println(<span class="hljs-string">&quot;在容器中的名称：&quot;</span> + name);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.5r5ogy7efn00.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<h4 id="2-ImportSelector-接口"><a href="#2-ImportSelector-接口" class="headerlink" title="2. ImportSelector 接口"></a>2. ImportSelector 接口</h4><p>编写一个类实现 <code>ImportSelector</code>  ，重写 <code>selectImports</code> 方法就可注册组件到容器，其返回值是要加入到容器中的类的全限定类名，以字符串数组形式返回</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyImportSelector</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ImportSelector</span> </span>&#123;<br>    <span class="hljs-comment">// 以数组形式返回要放入 ioc 容器中的类的全限定名称</span><br>    <span class="hljs-comment">// AnnotationMetadata：是当前 @Import 注解标注的类上的所有注解信息</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String[] selectImports(AnnotationMetadata importingClassMetadata) &#123;<br>        <span class="hljs-comment">// 返回全限定类名数组</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> String[]&#123;<span class="hljs-string">&quot;cn.yechen.bean.Color&quot;</span>, <span class="hljs-string">&quot;cn.yechen.bean.Red&quot;</span>&#125;;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>其中 AnnotationMetadata 参数是当前 @Import 注解标注的类上的所有注解信息，此时的配置类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@Import(&#123;MyImportSelector.class&#125;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConfig2</span> </span>&#123;<br>    <br>&#125;<br></code></pre></td></tr></table></figure>

<p>打断点测试就可看到该参数中保存的值</p>
<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.1ekm5p02nov4.png" srcset="/img/loading.gif" lazyload alt="DeBug结果"></p>
<p>测试</p>
<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.60e3e43mssw0.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<h4 id="3-ImportBeanDefinitionRegistrar-接口"><a href="#3-ImportBeanDefinitionRegistrar-接口" class="headerlink" title="3. ImportBeanDefinitionRegistrar 接口"></a>3. ImportBeanDefinitionRegistrar 接口</h4><p>通过一个类实现 <code>ImportBeanDefinitionRegistrar</code> 接口，重写 <code>registerBeanDefinitions</code> 方法，在方法中可以直接通过注册类注册 bean，此时还可以指定 bean 的 id</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyImportBeanDefinitionRegistrar</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ImportBeanDefinitionRegistrar</span> </span>&#123;<br>    <span class="hljs-comment">/*</span><br><span class="hljs-comment">        AnnotationMetadata：是当前 @Import 注解标注的类上的所有注解信息</span><br><span class="hljs-comment">        BeanDefinitionRegistry：bean 定义的注册类，可以通过该对象的方法 registerBeanDefinition 注册 bean</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">registerBeanDefinitions</span><span class="hljs-params">(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)</span> </span>&#123;<br>        <span class="hljs-comment">// 注册一个 Color 组件，id 名为 color</span><br>        registry.registerBeanDefinition(<span class="hljs-string">&quot;color&quot;</span>, <span class="hljs-keyword">new</span> RootBeanDefinition(Color.class));<br>        <span class="hljs-comment">// ImportBeanDefinitionRegistrar.super.registerBeanDefinitions(importingClassMetadata, registry);</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>





<h3 id="六、Spring-提供的-FactoryBean"><a href="#六、Spring-提供的-FactoryBean" class="headerlink" title="六、Spring 提供的 FactoryBean"></a>六、Spring 提供的 FactoryBean</h3><p>Spring 提供了一个 <code>FactoryBean</code> 接口，可以注册组件到 ioc 容器中，其中有三个方法</p>
<ul>
<li><code>getObject()</code> 可以将返回值是泛型中指定的类型，并且可以将返回值注册到 ioc 容器中</li>
<li><code>getObjectType()</code> 返回泛型中指定的类型的 class 对象</li>
<li><code>isSingleton()</code> 当前组件是否是单例的，是单实例的返回 true，是多实例就返回 false，默认是 true，即单实例</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ColorFactoryBean</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">FactoryBean</span>&lt;<span class="hljs-title">Color</span>&gt; </span>&#123;<br>    <span class="hljs-comment">// 返回一个 Color 对象，这个对象会添加到容器中</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> Color <span class="hljs-title">getObject</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Color();<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> Class&lt;?&gt; getObjectType() &#123;<br>        <span class="hljs-keyword">return</span> Color.class;<br>    &#125;<br><br>    <span class="hljs-comment">// 是否是单例，默认是单实例，返回值为 true，是单实例，返回 false，是多实例</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isSingleton</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-comment">// 默认返回 true</span><br>        <span class="hljs-keyword">return</span> FactoryBean.<span class="hljs-keyword">super</span>.isSingleton();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在配置类中注册 ColorFactoryBean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConfig2</span> </span>&#123;<br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> ColorFactoryBean <span class="hljs-title">colorFactoryBean</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ColorFactoryBean();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>测试一下：通过方法名获取 bean 时，从容器中获取到的对象是 FactoryBean 中指定的泛型，如果想要获取 FactoryBean 本身，可以在 bean 的 id 前加一个前缀 &amp; </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 测试 FactoryBean</span><br><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testFactoryBean</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-comment">// 获取容器</span><br>    AnnotationConfigApplicationContext context = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext(MyConfig2.class);<br><br>    <span class="hljs-comment">// 通过 name 获取 bean</span><br>    Object bean = context.getBean(<span class="hljs-string">&quot;colorFactoryBean&quot;</span>);<br>    <span class="hljs-comment">// 获取到的 bean 的类型是 class cn.yechen.bean.Color</span><br>    System.out.println(bean.getClass());<br><br>    <span class="hljs-comment">// 获取 FactoryBean 本身，可以在 bean 的 id 前加一个前缀 &amp;</span><br>    Object colorFactoryBean = context.getBean(<span class="hljs-string">&quot;&amp;colorFactoryBean&quot;</span>);<br>    System.out.println(colorFactoryBean.getClass());<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试：</p>
<p><img src="https://cdn.jsdelivr.net/gh/yechen-ops/image-hosting@master/20210916/image.5n64aio8z5s0.png" srcset="/img/loading.gif" lazyload alt="测试结果"></p>
<p>加上一个 &amp; 的原因是在 Spring 源码 <code>BeanFactory</code> 接口中指定了 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">BeanFactory</span> </span>&#123;<br>    <span class="hljs-comment">// 工厂 Bean 前缀</span><br>    String FACTORY_BEAN_PREFIX = <span class="hljs-string">&quot;&amp;&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="七、总结在容器中组件注册方法"><a href="#七、总结在容器中组件注册方法" class="headerlink" title="七、总结在容器中组件注册方法"></a>七、总结在容器中组件注册方法</h3><h4 id="1-开启包扫描"><a href="#1-开启包扫描" class="headerlink" title="1. 开启包扫描"></a>1. 开启包扫描</h4><p>对于自己写的类，可以根据不同的功能在类上加上 <code>@Component</code>、<code>@Controller</code>、<code>@Service</code>、<code>@Repository</code> 等注解，开启包扫描后就可将这些类注册到 ioc 容器中。</p>
<p>但是对于不是自己写的类，就不能使用这种方法了。</p>
<h4 id="2-Bean-注解"><a href="#2-Bean-注解" class="headerlink" title="2. @Bean 注解"></a>2. @Bean 注解</h4><p>在方法上使用 @Bean 注解，将自己或者第三方包里的组件注册到 ioc 容器</p>
<h4 id="3-Import-注解"><a href="#3-Import-注解" class="headerlink" title="3. @Import 注解"></a>3. @Import 注解</h4><p>快速给容器中导入一个组件，有三种导入方法：</p>
<ol>
<li>@Import(要导入到容器中的组件)；容器中就会自动注册这个组件，id 默认是全类名</li>
<li>ImportSelector：返回需要导入的组件的全限定类名数组</li>
<li>ImportBeanDefinitionRegistrar：手动注册 bean 到容器中</li>
</ol>
<h4 id="4-FactoryBean-接口"><a href="#4-FactoryBean-接口" class="headerlink" title="4. FactoryBean 接口"></a>4. FactoryBean 接口</h4><p>Spring 提供的工程 bean，写一个类实现 FactoryBean 接口，有方法可以注册组件。</p>
<h4 id="5-Conditional-注解"><a href="#5-Conditional-注解" class="headerlink" title="5. @Conditional 注解"></a>5. @Conditional 注解</h4><p>按照一定的条件进行判断，将满足条件的 bean 注册到容器中。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/SSM-%E6%A1%86%E6%9E%B6/">SSM 框架</a>
                    
                      <a class="hover-with-bg" href="/categories/SSM-%E6%A1%86%E6%9E%B6/Spring/">Spring</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/SSM-%E6%A1%86%E6%9E%B6/">SSM 框架</a>
                    
                      <a class="hover-with-bg" href="/tags/Spring/">Spring</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/09/25/%E8%B0%B7%E7%B2%92%E5%95%86%E5%9F%8E%E9%A1%B9%E7%9B%AE-2021-09-25-1-%E9%A1%B9%E7%9B%AE%E4%BB%8B%E7%BB%8D%E5%8F%8A%E5%9F%BA%E7%A1%80%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">1.项目介绍及基础环境搭建</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/09/15/hexo%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA-2021-09-15-Hexo-Fluid%E4%B8%BB%E9%A2%98%E7%BE%8E%E5%8C%96/">
                        <span class="hidden-mobile">Hexo-Fluid主题美化</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.3/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.1/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js" ></script>



  <script  src="/js/local-search.js" ></script>






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>














  
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiaoxuehua.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/caidai.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/love.js"></script>
<script src="//cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script>
<script src="//cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script>



<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>

  <!--动态线条背景-->
  <script type="text/javascript" color="70,119,184" opacity='1' zIndex="-2" count="200" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"left","width":200,"height":400},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
